//var db = require('../../../utils/db.js');
//var bbs = require('../../../utils/bbs.js');
var util = require('../../../utils/util.js');
const db = wx.cloud.database();
//获取应用实例
const app = getApp();
var navList = [{id: "good",title: "精华"},
  {id: "share",title: "分享"},
  {id: "ask",title: "问答"},
  {id: "topic",title: "发贴"}
];

Page({
  data: {
    activeIndex: 0,
    navList: navList,
    title: '话题列表',
    isAdmin: app.globalData.isAdmin,
    goodList: [],//缓存
    shareList: [],//缓存
    askList: [],//缓存
    postsList: [],//当前
    hidden: false,
    page: 1,
    limit: 20,
    tab: 'good',

    //以下为发贴的data
    hideComment: true,
    topicTab: 'share',
    topicTitle:'',
    content: '',
    files: [],
    modalHidden:true,

    //删除评论标识
    delIndex: null,
    delId: null,

    //以下为用户信息
    userInfo:null,
    logged: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  onLoad: function() {
    //===================用户登陆信息开始============================
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo
        })
        app.globalData.userInfo = res.userInfo;
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo
          })
        }
      })
    }
    //===================用户登陆信息结束============================
    this.findTopicList();

    //设置是否为管理员
    this.setData({
      isAdmin: app.globalData.isAdmin
    });
  },

  onPullDownRefresh: function() {
    //如果是评论不刷新
    if (this.data.tab == 'topic') {
      return;
    }
    this.findTopicList();
    console.log('下拉刷新', new Date());
  },


  onReachBottom: function() {
    //如果是评论不刷新
    if (this.data.tab == 'topic') {
      return;
    }

    this.lower();
    console.log('上拉刷新', new Date());
  },

  // 点击获取对应分类的数据
  onTapTag: function(e) {
    var that = this;
    var tab = e.currentTarget.id;
    var index = e.currentTarget.dataset.index;
    that.setData({
      activeIndex: index,
      tab: tab,
      page: 1
    });

    //如果是发贴
    if (tab =="topic")
    {
      that.setData({
        postsList: [],
        hideComment:false
      });

      return;
    }

    var postsList = null;
    if (tab == "good") {
      postsList=this.data.goodList;
    } else if (tab == "share")
    {
      postsList = this.data.shareList;
    } else if (tab == "ask") {
      postsList = this.data.askList;
    }
    that.setData({
      postsList: postsList,
      hideComment: true
    });
    
    if (null == postsList || postsList.length==0)
    {
      that.findTopicList();
    }
  },

  //获取文章列表数据
  findTopicList: function() {
    var that = this;
    var tab = that.data.tab;
    var page = that.data.page;
    var limit = that.data.limit;
    that.setData({
      hidden: false,
      hideComment: true
    });

    if (page == 1) {
      that.setData({
        postsList: []
      });
    }

    var filter = null;
    if ("share"==tab || "ask"==tab)
    {
      filter = { tab: tab };
    }else if("good" == tab)
    {
      filter = {"good":true};
    }

    wx.cloud.callFunction({
      name: 'pagination',
      data: {
        dbName: 'bbs_topic',
        pageIndex: page,
        pageSize: 10,
        filter: filter
      },
      success(res) {
        //更新数据
        that.setData({
          postsList: that.data.postsList.concat(res.result.data.map(function (item) {
            item.create_at = util.getDateDiff(new Date(item.create_at));
            return item;
          }))
        });

        //==============缓存开始===============
        if (tab=="good")
        {
          that.setData({
            goodList: that.data.postsList
          });
        }
        if (tab == "share") {
          that.setData({
            shareList: that.data.postsList
          });
        }
        if (tab == "ask") {
          that.setData({
            askList: that.data.postsList
          });
        }
        //==============缓存结束===============

        setTimeout(function () {
          that.setData({
            hidden: true
          });
        }, 300);
      },
      fail(){
        util.showErrorToast("失败了,请重试");
        that.setData({
          hidden: true
        });
      } 
    });
  },

  // 滑动底部加载
  lower: function() {
    console.log('滑动底部加载', new Date());
    var that = this;
    that.setData({
      page: that.data.page + 1
    });

    this.findTopicList({
      tab: that.data.tab,
      page: that.data.page
    });
  },

  //=======================删贴开始==========================
  delTopic: function(e) {
    //下标
    var index = e.currentTarget.dataset.idx;
    var id = e.currentTarget.dataset.id;
    this.setData({ modalHidden: false, delIndex: index, delId: id });
  },

  // 关闭--模态弹窗
  cancelDel: function () {
    this.setData({ modalHidden: true });
  },
  // 确认--模态弹窗
  confirmDel: function () {
    var that = this;
    var index = this.data.delIndex;
    var id = this.data.delId;

    //删除贴子
    db.collection('bbs_topic').doc(id).remove().then(res => {
      var tempList = that.data.postsList;

      //删除图片 
      var delTopic = tempList[index];
      var imgs = delTopic.imgs;
      if(null!=imgs && imgs.length>0)
      {
        wx.cloud.deleteFile({
          fileList: imgs,
          success: res => {
          },
          fail: res => {
          }
        })
      }

      //更新显示的列表
      tempList.splice(index, 1);
      that.setData({ postsList: tempList, modalHidden: true });
      wx.showToast({ title: "删除成功" });
      
      //================批量删除回复开始 ====================
      var filter = { 'topic_id': id };
      wx.cloud.callFunction({
        name: 'batchDel',
        data: {
          dbName: 'common_comment',
          filter: filter
        },
        success(res) {
          
        },
        fail() {
          
        }
      });
      //================批量删除回复结束 ====================

    });
  },

  //======================发贴开始===================================
  //选择图片
  chooseImage: function (e) {
    if (this.data.files.length >=1) {
      util.showErrorToast('只能上传1张图片')
      return false;
    }

    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        that.setData({
          files: that.data.files.concat(res.tempFilePaths)
        });
      }
    })
  },

  //上传图片(上传到云)
  uploadCloud: function () {
    var that = this;
    //临时目录
    const filePath = that.data.files[0];
    
    //文件扩展名
    var extName = filePath.match(/\.[^.]+?$/)[0];
    var currentTime = util.getCurrentTimeStr("yyyyMMddhhmmssS");
    var cloudPath = "upload/bbs/" + currentTime + Math.random() * 1000 + extName;
    
    wx.cloud.uploadFile({
      cloudPath,
      filePath,
      success: res => {
        that.savePost([res.fileID]);
      },
      fail: e => {
        console.error('[上传文件] 失败：', e)
        wx.showToast({
          icon: 'none',
          title: '上传失败',
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    });
  },

  //预览图片
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },

  //重置贴子
  resetPost: function() {
    this.setData({
      topicTitle: '',
      content: '',
      files: []
    });
  },
  //发表贴子
  publishPost: function (e) {
    
    //如果已经登陆,且还没有记录
    if (!this.logged && e.detail.userInfo) {
      this.setData({
        logged: true,
        userInfo: e.detail.userInfo
      });
      app.globalData.userInfo = e.detail.userInfo;
    }
    
    if (null == this.data.userInfo)
    {
      util.showErrorToast("匿名不能发贴");
      return;
    }

    let that = this;
    if (!this.data.topicTitle) {
      util.showErrorToast('请填写标题')
      return false;
    }
    //有图片
    if (this.data.files.length > 0)
    {
        //上传图片至云
        this.uploadCloud();
        return;
    }
    this.savePost([]);
  },

  //保存贴子
  savePost: function (imgs) {
    var newTopic =
    {
      "tab": this.data.topicTab,
      "title": this.data.topicTitle,
      "content": this.data.content,
      "good": false,
      "top": false,
      "reply_count": 0,
      "visit_count": 1,
      "create_at": util.getCurrentTimeStr(),
      "imgs": imgs,
      "_openid": app.globalData._openid,
      "author": {
        "loginname": this.data.userInfo.nickName,
        "avatar_url": this.data.userInfo.avatarUrl
      }
    };
    var that = this;

    db.collection('bbs_topic').add({
      data: newTopic,
      success: res => {
        
        that.setData({
          topicTitle: "",
          content: "",
          files: [],
          tab: that.data.topicTab,
          activeIndex: that.data.topicTab=="share"?1:2,
          page: 1
        });
        //发布成功后，刷新加载
        that.findTopicList();
      },
      fail: e => {
        wx.showToast({
          title: '发布错误',
        });
      }
    })
  },

  //radio切换贴子类型
  radioChange(event) {
    this.setData({
      topicTab: event.detail.value,
    })
  },

  bindInputTitle(event) {
    let value = event.detail.value;
    //判断是否超过50个字符
    if (value && value.length > 50) {
      return;
    }
    this.setData({
      topicTitle: event.detail.value,
    })
  },
  bindInputValue(event) {
    let value = event.detail.value;
    //判断是否超过200个字符
    if (value && value.length > 200) {
      return;
    }
    this.setData({
      content: event.detail.value,
    })
  }
  //======================发贴结束===================================
})